<script setup>
import { useApi } from "../../composables/useApi";
import showTost from "@/components/toast/index.js";
import * as XLSX from "xlsx";
import { storeToRefs } from "pinia";
import { useAppStore } from "../../store/app";
import moment from "moment";

const appStore = useAppStore();

const { nationArr, sexArr } = storeToRefs(appStore);
import { reactive, ref } from "vue";
import TeatherRightDrawaer from "@/pages/platform/components/teatherRightDrawaer.vue";
import ClassHeader from "@/pages/platform/components/classHeader.vue";
import ClassRightDrawear from "@/pages/platform/components/classRightDrawear.vue";

//基本数据list
let list = ref([]);
let page = ref(1);
let limit = ref(20);
let total = ref(0); //总数
const selected = ref([]);
let queryFrom = ref({ page: 1, limit: 20, title: "", name: "" });

const headers = [
  {
    title: "班级名称",
    key: "title",
    align: "start",
  },
  {
    title: "所属年级",
    key: "grade_title",
    align: "start",
  },
  {
    title: "班主任",
    key: "charge_name",
    align: "start",
  },
  {
    title: "副班主任",
    key: "vice_charge_name",
    align: "start",
  },
  {
    title: "语文老师",
    key: "lang_teacher_name",
    align: "start",
  },
  {
    title: "数学老师",
    key: "math_teacher_name",
    align: "start",
  },
  {
    title: "英语老师",
    key: "eng_teacher_name",
    align: "start",
  },
  {
    title: "学生人数",
    key: "studentNum",
    align: "start",
  },
  {
    title: "操作",
    align: "end",

    key: "options",
    sortable: false,
  },
];

const getList = async () => {
  const { data } = await useApi("/admin/Api.GradeClass/index").post(
    queryFrom.value
  );
  console.log(data);
  total.value = data.value.data.total;
  list.value = data.value.data.data.map((item) => {
    return {
      ...item,
      id: item.class_id,
    };
  });
};

const dialogFlag = ref(false);
// 头部表单回调
const onChange = (val) => {
  let data = JSON.parse(JSON.stringify(val));
  queryFrom.value = { ...queryFrom.value, ...data };
  getList();
};
const isConfirmDialogVisible = ref(false);
// 删除确认弹窗
const onHandleDelete = async (val) => {
  console.log(val);
  let ids = val.data.map((item) => item.class_id).toString();
  console.log(ids);
  const { data } = await useApi("/admin/Api.GradeClass/delete").post({
    class_id: ids,
  });
  console.log(data.value);
  if (data.value.status == 200) {
    showTost("删除成功", { duration: 3000, type: "success" });
    queryFrom.value.page = 1;
    isConfirmDialogVisible.value = false;
    if (val.type == "detail") {
      dialogFlag.value = false;
    }
    getList();
  }
};
const selectedItems = ref([]);

// 确认弹窗文本
const confirmMsg = ref("");

// 打开删除弹窗
const onHandleDialog = (type) => {
  if (type == "delete") {
    console.log(selectedItems);
    if (selectedItems.value.length == 0) return;
    let data = list.value.filter((item) =>
      selectedItems.value.find((val) => val == item.id)
    );
    console.log(data);
    currentOptionData.value = {
      data: data,
      type: "list",
    };
    confirmMsg.value = `确认删除${data
      .map((item) => item.title)
      .toString()}的信息吗`;
    isConfirmDialogVisible.value = true;
  } else {
    addDialogFlag.value = true;
  }
};
// 详情数据
const detailData = ref({});
const viewDetail = async (item) => {
  const { data } = await useApi("/admin/Api.GradeClass/detail").post({
    class_id: item.class_id,
  });
  console.log(data);
  detailData.value = data.value.data;
  dialogFlag.value = true;
};
// 添加教师弹窗falg
const addDialogFlag = ref(false);
const refVForm = ref();

// 下载模板
const downLoadTemplate = async () => {
  const { data } = await useApi("/admin/Base/downFile").post({ type: 1 });
  console.log(data.value);
  if (data.value.status == 200) {
    const link = document.createElement("a");
    link.href = data.value.data.fileUrl;
    link.download = data.value.data.fileName;
    link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click();
  }
};
// 新增取消回调
const resetForm = () => {
  refVForm.value?.reset();

  addDialogFlag.value = false;
};

const valid = ref(false);
const form = reactive({
  title: "",
  grade_title: "",
  charge_name: "",
  vice_charge_name: "",
  lang_teacher_name: "",
  math_teacher_name: "",
  eng_teacher_name: "",
  studentNum: "",
});
const confirmAddTeacher = async (args) => {
  console.log(valid.value);

  if (!valid.value) return;
  const { data } = await useApi("/admin/Api.GradeClass/add").post(form);
  if (data.value.status == 200) {
    refVForm.value?.reset();

    addDialogFlag.value = false;
    showTost("新增成功", { duration: 3000, type: "success" });
    queryFrom.value.page = 1;
    getList();
  } else {
    console.log(data.value.msg);
    // showTost("新增成功", {duration: 3000, type: "success"})

    showTost(data.value.msg, { duration: 3000, type: "error" });
  }
};
let sexList = ref(["男", "女"]);
const onHandleEdit = () => {
  queryFrom.value.page = 1;
  getList();
};
getList();
const required = (value, name) => !!value || `${name}为必填字段`;
const importExcelRef = ref(null);
const httpRequest = (e) => {
  let file = e.file; // 文件信息
  if (!file) {
    return false;
  } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
    // 格式根据自己需求定义
    this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
    return false;
  }
  const fileReader = new FileReader();
  fileReader.onload = (ev) => {
    try {
      const data = ev.target.result;
      const workbook = XLSX.read(data, {
        // 以字符编码的方式解析
        type: "binary",
        cellDates: true,
      });
      // 取第一张表
      console.log(workbook);
      const exlname = workbook.SheetNames[0];
      const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]); // 生成json表格内容
      console.log(exl);
      partPost(exl);
      // 将 JSON 数据挂到 data 里
      let arr = [];
      exl.forEach((item) => {
        arr.push(item.name);
      });
      console.log(arr);
    } catch (e) {
      console.log("error");
      return false;
    }
  };
  fileReader.readAsBinaryString(file);
};
const import_page = ref(1);
const import_limit = ref(10);
const import_percent = ref(0);
const loading = ref(false);

const partPost = async (tableData) => {
  let perdata = [];
  for (
    let i = (import_page.value - 1) * import_limit.value;
    i < import_page.value * import_limit.value;
    i++
  ) {
    if (tableData[i]) {
      perdata.push(tableData[i]);
    }
  }
  let total_page = Math.ceil(tableData.length / import_limit.value);
  import_percent.value = Math.ceil((import_page.value * 100) / total_page);
  loading.value = true;
  console.log(perdata);
  perdata = perdata.map((item) => {
    return {
      ...item,
      出生日期: convertExcelDateFormat(item, "出生日期"),
      入职日期: convertExcelDateFormat(item, "入职日期"),
    };
  });
  console.log(perdata);
  const { data } = await useApi("/admin/Api.Teacher/upload").post({
    list: perdata,
  });
  if (data.value.status == 200) {
    if (import_page.value <= total_page - 1) {
      import_page.value = import_page.value + 1;
      partPost(data);
    } else {
      // this.dialog.importDialogstatus = false;
      showTost("导入完成", { duration: 3000, type: "success" });
      addDialogFlag.value = false;
      queryFrom.value.page = 1;
      getList();
      loading.value = false;
    }
  }
  // importData(perdata).then(res => {
  //   if(res.status == 200){
  //     if(this.import_page <= total_page-1){
  //       this.import_page = this.import_page +1
  //       this.partPost(data)
  //     }else{
  //       this.dialog.importDialogstatus = false;
  //       this.$message({message: '导入完成', type: 'success'})
  //       this.index()
  //       this.loading = false
  //     }
  //   }
  // })
};

const onChangePage = (val) => {
  queryFrom.value.page = val.page;
  queryFrom.value.limit = val.limit;
  getList();
};
const convertExcelDateFormat = (row, columnName) => {
  //日期转换
  var date = row[columnName];
  if (date === undefined || date === null || date === "") {
    return null;
  }
  console.log(date);
  //非时间格式问题  返回Invalid date
  let retFormat = moment(date).format("YYYY-MM-DD");
  if (retFormat === "Invalid date") {
    return retFormat;
  }
  return moment(date).add(1, "days").format("YYYY-MM-DD");
};
const currentOptionData = ref({});
const drawaerDelete = async (val) => {
  console.log(val);
  currentOptionData.value = {
    data: [val],
    type: "detail",
  };
  confirmMsg.value = `确认删除${val.title}的信息吗`;
  isConfirmDialogVisible.value = true;
};
// 获取教师列表开始
const teacherList = ref([]);
const getTeacherList = async () => {
  const { data } = await useApi("/admin/Api.Teacher/indexList").post({});
  if (data.value.status == 200) {
    teacherList.value = data.value.data;
  }
};
getTeacherList();
// 获取教师列表结束

// 获取年级列表开始
const gradeList = ref([]);
const getGradeList = async () => {
  const { data } = await useApi("/admin/Api.Grade/indexList").post({});
  if (data.value.status == 200) {
    console.log(data.value.data);
    gradeList.value = data.value.data;
  }
};
getGradeList();
// 获取年级列表结束
</script>

<template>
  <div class="content">
    <class-right-drawear
      :gradeList="gradeList"
      :teacherList="teacherList"
      @onHandleDelete="drawaerDelete"
      @onHandleEdit="onHandleEdit"
      :detailData="detailData"
      @update:isDrawerOpen="dialogFlag = $event"
      :is-drawer-open="dialogFlag"
    />

    <ConfirmDialog
      v-model:isDialogVisible="isConfirmDialogVisible"
      :handleData="currentOptionData"
      @confirm="onHandleDelete"
      :confirm-msg="confirmMsg"
      :confirmation-question="confirmMsg"
      cancel-msg="Unsubscription Cancelled!!"
    />
    <!-- 头部 -->
    <class-header
      title="班级信息"
      button-text="添加班级"
      @onChange="onChange"
      @onHandle="onHandleDialog"
    ></class-header>

    <VDataTable
      v-model="selectedItems"
      :headers="headers"
      :items="list"
      :items-per-page="100"
      item-key="id"
      show-select
      class="text-no-wrap"
    >
      <template #item.password="{ item }">
        <div class="options-right-display d-flex align-center">
          <div class="d-flex flex-column ms-3">
            {{ item.password || "******" }}
          </div>
        </div>
      </template>
      <template #item.options="{ item }">
        <div class="d-flex align-center options-right-display">
          <div class="d-flex flex-column ms-3 cursor-pointer">
            <i @click="viewDetail(item)" class="ri-menu-line"></i>
          </div>
        </div>
      </template>
    </VDataTable>
    <PaginationVue
      @onChange="onChangePage"
      :current-page="queryFrom.page"
      :page-size="queryFrom.limit"
      :total="total"
    />

    <!--    添加对话框-->
    <VDialog :persistent="true" max-width="600" :model-value="addDialogFlag">
      <div class="dialog-body" style="width: 600px">
        <AppDrawerHeaderSection
          title="添加班级"
          @cancel="addDialogFlag = false"
        />
        <VDivider style="background-color: red" class="v-divider" />
        <VCard>
          <PerfectScrollbar :options="{ wheelPropagation: false }" class="h-60">
            <VCardText>
              <VForm
                v-model="valid"
                ref="refVForm"
                @submit.prevent="confirmAddTeacher"
              >
                <VRow>
                  <VCol cols="6">
                    <VTextField
                      v-model="form.title"
                      label="班级名称*"
                      :rules="[(val) => required(val, '班级名称')]"
                      placeholder="请输入班级名称"
                    >
                      <template v-slot:label>
                        <span>班级名称</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </VTextField>
                  </VCol>
                  <VCol cols="6">
                    <v-autocomplete
                      v-model="form.grade_id"
                      :items="gradeList"
                      item-title="title"
                      item-value="grade_id"
                      placeholder="请选择所属年级"
                      label="所属年级*"
                      :rules="[(val) => required(val, '所属年级')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>所属年级</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </v-autocomplete>
                  </VCol>

                  <VCol cols="6">
                    <v-autocomplete
                      v-model="form.charge_id"
                      :items="teacherList"
                      item-title="real_name"
                      item-value="teacher_id"
                      placeholder="请选择班主任"
                      label="班主任*"
                      :rules="[(val) => required(val, '班主任')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>班主任</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </v-autocomplete>
                  </VCol>
                  <VCol cols="6">
                    <v-autocomplete
                      v-model="form.vice_charge_id"
                      :items="teacherList"
                      item-title="real_name"
                      item-value="teacher_id"
                      placeholder="请选择副班主任"
                      label="副班主任*"
                      :rules="[(val) => required(val, '副班主任')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>副班主任</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </v-autocomplete>
                  </VCol>

                  <VCol cols="6">
                    <v-autocomplete
                      v-model="form.lang_teacher_id"
                      :items="teacherList"
                      item-title="real_name"
                      item-value="teacher_id"
                      placeholder="请选择语文教师"
                      label="语文教师*"
                      :rules="[(val) => required(val, '语文教师')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>语文教师</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </v-autocomplete>
                  </VCol>

                  <VCol cols="6">
                    <v-autocomplete
                      v-model="form.math_teacher_id"
                      :items="teacherList"
                      item-title="real_name"
                      item-value="teacher_id"
                      placeholder="请选择副数学教师"
                      label="数学教师*"
                      :rules="[(val) => required(val, '数学教师')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>数学教师</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </v-autocomplete>
                  </VCol>
                  <VCol cols="6">
                    <v-autocomplete
                      v-model="form.eng_teacher_id"
                      :items="teacherList"
                      item-title="real_name"
                      item-value="teacher_id"
                      placeholder="请选择英语教师"
                      label="英语教师*"
                      :rules="[(val) => required(val, '英语教师')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>英语教师</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </v-autocomplete>
                  </VCol>

                  <VCol cols="12">
                    <div class="d-flex justify-end">
                      <VBtn   color="secondary"
                              type="reset"
                              variant="tonal" class="me-4" @click="resetForm">
                        取消
                      </VBtn>
                      <VBtn type="submit" color="primary" class="me-4">
                        添加
                      </VBtn>
                    </div>
                  </VCol>
                </VRow>
              </VForm>
            </VCardText>
          </PerfectScrollbar>
        </VCard>
      </div>
    </VDialog>
  </div>
</template>

<style lang="scss" scoped>
.dialog-body {
  background: rgb(var(--v-theme-surface));
}
</style>
